﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace KC.Business.Net
{
	public static class Web
	{
		/// <summary>Options used for Web methods that use Hyperlinks</summary>
		public enum HyperlinkOption { All, Broken, Working }

		/// <summary>Gets a list of broken IMG tags in an HTML string.</summary>
		/// <param name="Html">HTML code to parse</param>
		/// <returns>List of IMG tags in the HTML which match the given HyperLinkOption</returns>
		public static List<string> BuildListOfImgTags(string Html, HyperlinkOption hlo)
		{ return GetLinks(GetImagesFromHtml(Html), hlo); }
		/// <summary>Extracts all hyperlinks from an HTML body.</summary>
		/// <param name="HtmlBody">HTML body</param>
		/// <returns>List of all hyperlinks contained therein</returns>
		public static List<string> GetLinksFromHtml(string Body)
		{
			List<string> list = new List<string>();
			foreach (Match m in Regex.Matches(Body, @"(<a.*?>.*?</a>)", RegexOptions.Singleline)) {
				Match m2 = Regex.Match(m.Groups[1].Value, @"href=\""(.*?)\""", RegexOptions.Singleline);
				if (m2.Success && !m2.Groups[1].Value.ToLower().Contains("mailto:") && m2.Groups[1].Value.Contains("://"))
					list.Add(m2.Groups[1].Value); }
			return list;
		}
		/// <summary>Gets a list of Images in an HTMl string.</summary>
		/// <param name="Body">HTML code to parse</param>
		/// <returns>List of Images in the HTML</returns>
		public static List<string> GetImagesFromHtml(string Body)
		{
			if (string.IsNullOrEmpty(Body)) throw new ArgumentNullException("Body");

			List<string> links = new List<string>();
			foreach (Match m in Regex.Matches(Body, KC.Overhead.Constants.RegExes.UrlRegex_Image))
				links.Add(m.Value);
			return links;
		}
		/// <summary>Filters a list of links by their operational status</summary>
		/// <param name="links">Links to parse</param>
		/// <param name="hlo">Option dictating which links to return</param>
		/// <returns>List of links that match the options passed in</returns>
		public static List<string> GetLinks(List<string> links, HyperlinkOption hlo)
		{
			if (links == null)
				throw new ArgumentNullException("links", "Links cannot be null");
			if (links.Count == 0)
				return new List<string>();
			if (hlo == HyperlinkOption.All) return links;

			List<string> BrokenLinks = new List<string>();
			foreach (string link in links)
				using (System.Net.WebClient wc = new System.Net.WebClient())
					try {
						wc.DownloadData(link);
						if (hlo == HyperlinkOption.Working) BrokenLinks.Add(link); }
					catch { if (hlo == HyperlinkOption.Broken) BrokenLinks.Add(link); }
			return BrokenLinks;
		}

	}
}
